package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;

import com.alipay.sdk.app.AuthTask;
import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.alipay.ALiKeys;
import com.digitalchina.lxnsy.alipay.AuthResult;
import com.digitalchina.lxnsy.alipay.OrderInfoUtil2_0;
import com.digitalchina.lxnsy.api.BusinessAccount;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.PointVO;
import com.digitalchina.lxnsy.entity.UserVO;
import com.digitalchina.lxnsy.toolkit.ActivityTaskManager;
import com.digitalchina.lxnsy.toolkit.DateStyle;
import com.digitalchina.lxnsy.toolkit.DateUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.xml.UserXML;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;


import static com.digitalchina.lxnsy.constant.Constant.MSG_SET_ALIAS;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/12/2 11:46
 * 修改备注：
 * ================================================
 */
public class LoginGuideActivity extends BaseActivity {

    private static final int WX_AUTH = 1;
    private static final int SDK_AUTH_FLAG = 2;

    String openId = "";
    String unionid = ""; // 微信ID 或者支付宝userId
    String accountType = "";

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_login_guide);
        setTitle("登录/注册");
    }

    @Override
    public void initMember() {

    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                dismissDialog();
                switch (msg.what) {
                    case WX_AUTH:
                        login3rd("WX", openId);
                        break;
                    case SDK_AUTH_FLAG:
                        AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                        String resultStatus = authResult.getResultStatus();

                        // 判断resultStatus 为“9000”且result_code
                        // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                        if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                            // 获取alipay_open_id，调支付时作为参数extern_token 的value
                            // 传入，则支付账户为该授权账户
                            unionid = authResult.getuserId();
                            openId = authResult.getAlipayOpenId();
                            login3rd("ZFB", authResult.getuserId());
                        } else {
                            // 其他状态值则为授权失败
                            showToast("授权失败");
                        }
                        break;

                    case MSG.MSG_LOGIN_BY_3RD_SUCCESS: // 登录成功
                        showToast("登录成功");
                        UserVO userVO = FastJsonUtil.getBean(msg.obj.toString(), "body", "", UserVO.class);
                        List<PointVO> pointVOList = FastJsonUtil.getListBean(msg.obj.toString(), "body", "rewardPointDetailList", PointVO.class);
                        LogUtils.e(userVO);
                        //个人信息存储
                        UserXML.setUserVO(LoginGuideActivity.this, userVO);
                        setAlias(userVO.getUseraccid().replace("-", ""));

                        // 注册为个人用户
                        if (userVO.getUserType().equals(Constant.USER_TYPE_PERSON) || (userVO.getUserType().equals(Constant.USER_TYPE_EXPERT)) && !userVO.getIsAudit().equals("3")) {

                            UserXML.setTodayLogin(LoginGuideActivity.this, DateUtil.getCurrentDate(DateStyle.YYYY_MM_DD));
                            UserXML.setLoginStatus(LoginGuideActivity.this, UserXML.USER_IS_LOGIN_VALUE);

                            if (ActivityTaskManager.getInstance().size() > 1) {
                                Intent i = new Intent();
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("pointVOList", (Serializable) pointVOList);
                                i.putExtras(bundle);
                                setResult(1, i);
                                finish();
                            } else {
                                GotoUtil.gotoActivity(LoginGuideActivity.this, MainActivity.class, true, "pointVOList", pointVOList);
                            }
                        } else {
                            // 注册为专家用户
                            GotoUtil.gotoActivity(LoginGuideActivity.this, SaveExpertInfoActivity.class, true);
                        }
                        break;
                    case MSG.MSG_LOGIN_BY_3RD_FIELD:
                        Map<String, String> map = new HashMap<>();
                        map.put("ID", unionid);
                        map.put("openId", openId);
                        map.put("accountType", accountType);
                        if (msg.arg1 == 500017) {
                            GotoUtil.gotoActivity(LoginGuideActivity.this, RegisterTypeSelectActivity.class, true, "map", map);
                        } else
                            showToast(msg.obj.toString());
                        break;

                    case MSG_SET_ALIAS:
                        LogUtils.e("Set alias in handler.");
                        JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                        break;
                }
            }
        };
    }


    private void setAlias(String alias) {
        LogUtils.e(alias);
        if (TextUtils.isEmpty(alias)) {
            LogUtils.e("alias is empty");
            return;
        }
        if (!Utils.isValidTagAndAlias(alias)) {
            LogUtils.e("alias is not valid");
            return;
        }

        //调用JPush API设置Alias
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }


    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    LogUtils.e(logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LogUtils.e(logs);
                    if (Utils.isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        LogUtils.e("No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    LogUtils.e(logs);
            }

        }

    };

    /**
     * @param accountType 固定传WX或ZFB, WX（微信） ZFB （支付宝）
     * @param userId      第3方帐户唯一标识 微信为openId 支付宝为 user_id
     */
    private void login3rd(String accountType, String userId) {
        this.accountType = accountType;
        BusinessAccount.loginBy3rd(this, accountType, userId, mHandler);
    }

    @Override
    public void callBack(Object object) {

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.btn_register, R.id.btn_login_acc, R.id.btn_login_msg,R.id.btn_admin, R.id.iv_wx, R.id.iv_alipay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_register:
                GotoUtil.gotoActivity(LoginGuideActivity.this, RegisterTypeSelectActivity.class, true);
                break;
            case R.id.btn_login_acc:
                GotoUtil.gotoActivity(LoginGuideActivity.this, LoginActivity.class, true);
                break;
            case R.id.btn_login_msg:
                GotoUtil.gotoActivity(LoginGuideActivity.this, LoginCodeActivity.class, true);
                break;
            case R.id.btn_admin:
                GotoUtil.gotoActivity(LoginGuideActivity.this, LoginAdminActivity.class, true);
                break;
            case R.id.iv_wx:

                break;
            case R.id.iv_alipay:
                openAliPay();
                break;
        }
    }

    // 支付宝登录
    private void openAliPay() {

        /*
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * authInfo 的获取必须来自服务端；
         */
        Map<String, String> authInfoMap = OrderInfoUtil2_0.buildAuthInfoMap(ALiKeys.PID, ALiKeys.APPID, ALiKeys.TARGET_ID, false);
        String info = OrderInfoUtil2_0.buildOrderParam(authInfoMap);

        String privateKey = ALiKeys.RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(authInfoMap, privateKey, false);
        final String authInfo = info + "&" + sign;
        Runnable authRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(LoginGuideActivity.this);
                // 调用授权接口，获取授权结果
                String result = authTask.auth(authInfo, true);
                Map<String, String> map = AuthResult.a(result);

                Message msg = new Message();
                msg.what = SDK_AUTH_FLAG;
                msg.obj = map;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }

}
